package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: HuangQi
 * @date: Created in 11:58 2023/9/6
 * @description: 菜品管理控制层
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("新增菜品：{}", dishDto);
        dishService.saveWithFlavors(dishDto);
        return R.success("保存成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("菜品信息分页查询：page:{},pageSize:{},name:{}", page, pageSize, name);
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        //构建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);

            Long categoryId = dish.getCategoryId(); //分类id
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());


        dishDtoPage.setRecords(list);


        return R.success(dishDtoPage);
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        log.info("根据id查询菜品信息和对应的口味信息：id:{}", id);
        DishDto dishDto = dishService.getByIdWithFlavors(id);
        return R.success(dishDto);
    }


    /**
     * 更新菜品信息和对应的口味信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("更新菜品信息和对应的口味信息：{}", dishDto);
        dishService.updateWithFlavors(dishDto);
        return R.success("更新成功");
    }

    /**
     * 菜品批量起售和停售
     *
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateByIds(@RequestParam("ids") List<Long> ids, @PathVariable Integer status) {
        log.info("菜品批量起售和停售：ids:{}", ids);
        if (status == 0) {
            //停售,如果有关联的套餐在起售中,则不能停售
            boolean flag = hasOnUpSetmeal(ids);
            if (flag) {
                return R.error("所选菜品中有关联的套餐在起售中,不能停售");
            }
        }
        List<Dish> dishList = ids.stream().map(id -> {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            return dish;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
        return R.success("更新成功");
    }


    /**
     * 菜品批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteBatch(@RequestParam("ids") List<Long> ids) {
        log.info("菜品批量删除：ids:{}", ids);
        //如果有关联的套餐在起售中,则不能删除
        boolean flag = hasOnUpSetmeal(ids);
        if (flag) {
            return R.error("所选菜品中有关联的套餐在起售中,不能删除");
        }
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }


    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("查询菜品信息category_id:{}", dish);

        //构建查询条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加状态条件
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = null;
        dishDtoList = list.stream().map(d -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(d, dishDto);
            //设置分类名称
            Long categoryId = d.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            //查询菜品对应的口味
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, d.getId());
            dishDto.setFlavors(dishFlavorService.list(lambdaQueryWrapper));
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }


    /**
     * 根据菜品id查询是否有关联的套餐在起售中
     *
     * @param ids
     * @return
     */
    private boolean hasOnUpSetmeal(List<Long> ids) {
        for (Long id : ids) {
            //查询套餐菜品表中是否有含有该菜品的套餐
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getDishId, id);
            List<SetmealDish> list = setmealDishService.list(queryWrapper);
            if (list != null && list.size() > 0) {
                //有所属套餐,查询套餐是否停售
                for (SetmealDish setmealDish : list) {
                    Long setmealId = setmealDish.getSetmealId();
                    Setmeal setmeal = setmealService.getById(setmealId);
                    if (setmeal.getStatus() == 1) {
                        //套餐在起售中,不能停售
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
